// pages/postDetail/posDetail.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import { goBack, jump,setStorage,getStorage } from "../../utils/utils";
import request from "../../utils/request";
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromShare:false,
    nodata:'没有了~',
    placeholder:'你就是下一个热评~',
    showNodata:false,
    isfouse:false,
    bottomHeight:0,
    detail:{},
    commentlist:[],
    pages:0,
    current:1,
    content:'',
    totalComment:0,
    parentId:0,
    subParentId:0, //二级评论被回复人的id
    panelData:{},
    openIndex:-1,
    platform: null,
    // 是否是洼刘用户
		isWaliu: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options?.inviteData) {
			setStorage('inviteData', options?.inviteData)
			console.log('分享人数据：', options.inviteData)
		}
    let {postId,isPost,fromShare} = options

    console.log('postId',postId);
    const systemInfo = wx.getSystemInfoSync()
    this.setData({
      platform: systemInfo.platform,
      fromShare
    })
    this.getPostDetail(postId)
    this.getCommentList(postId)
		// 获取用户是否是洼刘用户
		this.getWaliu()

  
    if(isPost){
      this.setData({
        isPost
      })
    }
  },
  // 获取用户是否是洼刘用户
	async getWaliu() {
		let isWaliu = false
		if (app.isLogin()) {
      // const res = await request.get(api.isWaliu, {}, { loading: false })
      const res = {
				httpStatus: 200,
				data: false
			}
			if (res?.httpStatus === 200) {
				isWaliu = res?.data
			}
		}
		this.setData({
			isWaliu
		})
	},
  //获取帖子评论列表
  getCommentList: async function(id){
    let {current,commentlist,openIndex} = this.data
    const res = await request.get(api.getCommentList,{id,page: current})
    console.log('commentlistres',res);
    let data = res.data
    if(res.httpStatus==200){
      console.log('openIndex',openIndex);
      console.log('commentlist',commentlist);
      this.setData({
        pages:data.pages,
        totalComment:data.total,
        commentlist:commentlist.concat(data.records),
        panelData:openIndex<0?{}:data.records[openIndex]
      })
    }
  },
  //获取帖子详情
  getPostDetail: async function(id){
    const res = await request.get(api.getPostDetail,{id},{loading:false})
    console.log('deres',res);
    const {fromShare} = this.data
    if(res.httpStatus==200){
      this.setData({
        detail:res.data
      })

      if(fromShare){
        // 从分享进入 没有权限去圈子首页
        if(!res.data.allow){
          jump('circleHome')
          return
        }
      }
    }
  },
  //点击图片放大预览
  clickImage: function(e){
    let urls = this.data.detail.picUrls
    let item = e.currentTarget.dataset.item
    wx.previewImage({
      urls,
      current:item
    })
  },

  //输入框变化
  onTextAreaChange:function(e){
    let value = e.detail.value
    console.log('value',value);
    this.setData({
      content:value
    })
  },

  //添加评论
  addMyComment: async function(){
    let id = this.data.detail.id
    let {content,parentId,placeholder,highLight, subParentId} = this.data
    if(content==''){
      wx.showToast({
        title: '请输入文字',
        icon:'none'
      })
      return
    }

    let param = {
      content,
      dynamicId:id
    }

    //二级评论
    if(parentId!==0){
      content = content
      param = {
        content,
        parentId,
        highLight,
        subParentId,
        dynamicId:id
      }
    }

    const res = await request.post(api.addComment,param)
    if(res.httpStatus==200){
      this.setData({
        commentlist:[],
        current: 1
      })
      this.getCommentList(id)

      this.setData({
        isfouse:false,
        parentId:0,
        content:'',
      })
      this.getPostDetail(id)
    }
    console.log('添加评论',res);
  },

  //关闭评论详情面板
  hideShareSheet:function(){
    this.setData({
      openIndex:-1
    })
  },
  

  //显示textarea自动聚焦
  focusTextArea:function(e){ 
    console.log('ee',e.detail.height);
    let {bottomHeight} = this.data
    if(bottomHeight==0&&e.detail.height>0){
      this.setData({
        bottomHeight:e.detail.height,
      })
    }
  },

  //改变键盘高度
  // changeKeyBoardH:function(e){
  //   let {bottomHeight} = this.data
  //   console.log('h',e.detail.height);
  //   let h = e.detail.height
  //   if(h==0){
  //     this.setData({
  //       bottomHeight:h,
  //       isfouse:false,
  //       content:''
  //     })
  //   }
  // },
  //显示输入框
  showTextArea:function(){
    this.setData({
      isfouse:true
    })
  },
  //失去焦点
  blurTextArea:function(){
    console.log('blur',11);
    this.setData({
      isfouse:false
    })
  },
  //点击头像文本打开二级评论框
  openInputPanle:function(e){
    let {item,item2} = e.currentTarget.dataset
    // console.log('item',item);
    // console.log('item2',item2);
    let str = item2?item2.name:item.name
    this.setData({
      isfouse:true,
      parentId:item.id,
      subParentId:item2?item2.id:0,
      highLight: str,
      placeholder: '回复@'+ str +'：'
    })
  },
  //定位到评论
  jumpToComment:function(){
    wx.pageScrollTo({
      selector: '#comment',
    })
  },
  //打开评论详情面板
  clickComment2:function(e){
    this.shareSheet.show()
    let {item,index} = e.currentTarget.dataset
    this.setData({
      panelData:item,
      openIndex:index
    })
  },

  //点赞评论
  likeComment:async function(e){
    console.log('e',e.currentTarget.dataset.item);
    let {item,index,index2} = e.currentTarget.dataset
    let {like,id,parentId} = item
    let {commentlist,openIndex} = this.data

    let param = like?{deleted:1,likedId:id,type:2}:{likedId:id,type:2}
    let title = like?'已取消':'已点赞'
    
    const res = await request.post(api.likePostOrComment,param,{loading:false})
    if(res.httpStatus==200){
      if(parentId==0){
        //点赞一级评论
        commentlist[index].like = !like
        like?commentlist[index].likeTime--:commentlist[index].likeTime++
      }else{
        //点赞二级评论
        commentlist[index].child[index2].like = !like
        like?commentlist[index].child[index2].likeTime--:commentlist[index].child[index2].likeTime++
      }
      
      this.setData({
        commentlist,
        panelData:openIndex<0?{}:commentlist[openIndex]
      })
      wx.showToast({
        title,
        icon:'none'
      })
    }
  },
  //点赞帖子或取消点赞帖子
  likePost: async function(){
    let {like,id} = this.data.detail
    let param = like?{deleted:1,likedId:id,type:1}:{likedId:id,type:1}
    let title = like?'已取消':'已点赞'
    const res = await request.post(api.likePostOrComment,param,{loading:false})
    if(res.httpStatus==200){
      this.getPostDetail(id)
      wx.showToast({
        title,
        icon:'none'
      })
    }
  },
  // 关注&取关用户
  async followUser(e) {
    if (this.loading) return
    this.loading = true
    const info = this.data.detail
    if (info.follow && e !== false) {
      this.loading = false
      this.followModal.show()
      return
    }
    const res = await request.post(
      (info.follow ? api.cancleFollow : api.follow) + info?.userId,
      null,
      { loading: false }
    )
    if (res?.httpStatus === 200 || res?.msg === '已关注') {
      this.getPostDetail(info.id)
      this.loading = false
      setTimeout(() => {
        wx.showToast({
          icon: 'none',
          title: info.follow ? '取消成功' : '关注成功',
        })
      })
      this.followModal.hide()
    } else {
      this.loading = false
    }
    this.info = null
  },
  // 取关确认
  followConfirm() {
    this.followUser(false)
  },
  //去主页
  toHomePage:function(){
    let {userId} = this.data.detail
    wx.navigateTo({
      url: `/pages/home/home?id=${userId}`,
    })
  },
  // 跳转到勋章墙页面
  jumpMedalWall() {
    const { detail } = this.data
    wx.navigateTo({
      url: `/pages/medalWall/medalWall?userId=${detail?.userId}`,
    })
  },
  // 设为精选&取消精选
  async featured() {
    if (this.loading) return
    this.loading = true
    const dataset = this.data.detail
    const res = await request.post(api.postDelete, {
      id: dataset?.id,
      featured: dataset?.featured ? 0 : 1,
    }, { loading: false })
    if (res?.httpStatus === 200 || res?.data) {
      this.getPostDetail(dataset?.id)
      this.loading = false
      setTimeout(() => {
        wx.showToast({
          icon: 'none',
          title: dataset?.featured ? '已取消精选' : '已设为精选',
        })
      })
      this.sheet.hide()
    } else {
      this.loading = false
    }
  },
  // 删除提示框
  deleteTip() {
    this.deleteModal.show()
  },
  // 删除帖子
  async deletePost() {
    const id = this.data.detail.id
    const res = await request.post(api.postDelete, {
      id,
      deleted: 1
    })
    if (res?.httpStatus === 200) {
      this.setData({
        deleteId: null,
      })
      this.deleteModal.hide()
      this.sheet.hide()

      // 更新父级页面删除状态
      this.updatePrePage(id)

      wx.showToast({
        icon: 'none',
        title: '删除成功',
      })
      setTimeout(() => {
        goBack()
      }, 500)
    }
  },
  // 打开操作弹窗
  showSheet() {
    this.sheet.show()
  },
  // 关闭操作弹窗
  hideSheet() {
    this.sheet.hide()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.shareSheet = this.selectComponent('#shareSheet')
    this.deleteModal = this.selectComponent('#deleteModal')
    this.followModal = this.selectComponent('#followModal')
    this.sheet = this.selectComponent('#sheet')
    let {isPost} = this.data
    if(isPost){
      setTimeout(()=>{
       this.jumpToComment()
      },500)
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 更新父级页面帖子数据
    this.updatePrePage()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  // 点击返回
  handleBack(){
    goBack()
    // 更新父级页面帖子数据
    this.updatePrePage()
  },
  /**
   * 更新父级页面帖子数据
   * @param {*} id 帖子id
   */
  updatePrePage(id) {
    const pages = getCurrentPages()
    const prePage = pages[pages.length - 2]
    if ([
      'pages/home/home',
      'pages/circle/circle',
      'pages/circleHome/circleHome'
    ].includes(prePage?.route)) {
      const listName = prePage.route === 'pages/circleHome/circleHome'
        ? 'postList' : 'list'
      if (id) {
        prePage.setData({
          [listName]: prePage.data[listName].filter(item => {
            return item.id !== id
          })
        })
      } else {
        const { detail = {} } = this.data
  
        console.log(detail)
        prePage.setData({
          [listName]: prePage.data[listName].map(item => {
            if (item.id === detail.id) {
              item.like = detail.like
              item.likes = detail.likes
              item.comments = detail.comments
              item.featured = detail.featured
            }
            return item
          })
        })
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let postId = this.data.detail.id
    this.setData({
      commentlist:[],
      current: 1,
    })
    this.getPostDetail(postId)
    this.getCommentList(postId)
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
    let {current,pages} = this.data
    let {id} = this.data.detail
    console.log('id',id);
    if(current<pages){
      current++
      this.setData({
        current
      })
      this.getCommentList(id)
    }else{
      this.setData({
        showNodata:true
      })
    }
  },

  // 用户点击右上角分享
	onShareAppMessage(e) {
    const userId = getStorage('userId') || ''
    const {detail} = this.data
    let imageUrl = ''
    if(detail.shareType>2||detail.shareType==2){
      imageUrl = detail.picUrls[1]
    }else{
      imageUrl = detail.picUrls[0]||'https://image-classify.daieco.com/kejian-quanzi/qpUkToC5kE4bffc4952cbd9cd5b16b5ec0863e5c733e.png'
    }
    let title = detail.content.length>12?detail.content.substring(0,14)+'...':detail.content
    let path = `/pages/postDetail/postDetail?postId=${detail.id}&fromShare=true&inviteData=${userId}`
    return shareOptions('default', e, title, path, imageUrl)
	},
})